package com.cqs.leetcode.bit;

import com.google.common.base.Stopwatch;

/**
 * @author lixiaowen
 * @create 2019-12-18
 */
public class BitwiseANDNumbersRange201 {


    public int rangeBitwiseAnd(int m, int n) {
        if (m == n) return m;
        int count = 0;
        while (n != m) {
            n >>= 1;
            m >>= 1;
            ++count;
        }
        return n << count;
    }

    public int rangeBitwiseAnd2(int m, int n) {
        int result = m;
        //i > 0 防止出现 Integer.MAX_VALUE+1 = 0xFFFFFFFF = Integer.MIN_VALUE 溢出
        //result ==0 提前结束循环
        for (int i = m + 1; i > m && i <= n && result != 0; i++) {
            result = result & i;
        }
        return result;
    }

    public static void main(String[] args) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        BitwiseANDNumbersRange201 bit = new BitwiseANDNumbersRange201();

        //System.out.println(bit.rangeBitwiseAnd(700000000,Integer.MAX_VALUE));
        System.out.println(bit.rangeBitwiseAnd(2147483646, 2147483647));
        System.out.println(bit.rangeBitwiseAnd(2147483647, 2147483647));
//        System.out.println(bit.rangeBitwiseAnd(5,7));
        stopwatch.stop();
        System.out.println(stopwatch.elapsed());
        System.out.println(0x7FFFFFFF & 12345);

//        int n = 0x12345678;
//
//        for (int i = 0; i < 32; i++) {
//            System.out.println(n>>i);
//        }
    }
}
